import {Command} from '../constant';
import {Dispatch} from 'typings';
import {IAllReducerProps} from '../types';
import {getReducerData} from '@/redux/store';
import api from 'api';
import {extraPathsValue} from '@/redux/util';
import Taro from '@tarojs/taro';
import dayjs from 'dayjs';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },
    async placeOrder() {
      const {
        main: {list},
      } = getData();
      if (list.length <= 0) return;
      const items = list.filter((e) => e.checked);
      const toBay = await api.MyGiftPackController.freeBuy({
        goodsInfoIds: items.map((e) => e.goodsInfoId),
        customerCollection: true,
        customerCollectionId: items.map((e) => e.id),
      });
      Taro.navigateTo({
        url: '/pages/package-C/order/order-confirm-gift/index',
      });
    },
    async page(reset = false) {
      const {searchParams, list, allcheck} = getData().main;
      const result = await api.CollectionCabineController.getCabinepage(searchParams);
      const today = dayjs();
      result.content.forEach((e) => {
        const endDay = dayjs(e.expiresTime).diff(today, 'day');
        Reflect.set(e, 'endDay', endDay);
        if (searchParams.prizeStatus == 1) {
          Reflect.set(e, 'checked', false);
          if (allcheck) Reflect.set(e, 'checked', allcheck);
        }
      });
      const newList = reset ? result.content : [...list, ...result.content];

      action.commonChange('main.list', newList);
      action.commonChange('main.status', result.empty ? 'none' : result.last ? 'end' : 'ready');
    },
    async check(item: any, i: number) {
      const {list} = getData().main;
      const result = await api.CollectionCabineController.getCollection(item.id);
      Taro.showToast({
        icon: 'none',
        title: '领取成功',
      });
      const newList = JSON.parse(JSON.stringify(list));
      newList.splice(i, 1);
      action.commonChange('main.list', newList);
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageICollectionCabinetMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
